package org.meetunexpectedly.service.middleground.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.meetunexpectedly.entity.middleground.*;
import org.meetunexpectedly.entity.vo.Result;
import org.meetunexpectedly.mapper.middleground.RoleMapper;
import org.meetunexpectedly.service.middleground.PermissionService;
import org.meetunexpectedly.service.middleground.RolePermissionService;
import org.meetunexpectedly.service.middleground.RoleService;
import org.meetunexpectedly.service.middleground.UserRoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 角色服务接口实现类
 * @Author: pupil
 * @Date: 2024/09/03 下午 5:29
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @Override
    public List<Tree> tree() {
        List<Tree> trees = permissionService.list(null).stream().map(permission -> {
            Tree tree = new Tree();
            BeanUtils.copyProperties(permission, tree);
            tree.setTitle(permission.getName());
            tree.setSpread(true);
            return tree;
        }).collect(Collectors.toList());

        // 找到根节点
        List<Tree> parent = trees.stream().filter(tree -> tree.getPId().compareTo(0L) == 0).collect(Collectors.toList());
        for (Tree tree : parent) {
            findChildren(tree, trees);
        }

        return parent;
    }

    @Override
    @Transactional // 开启事务
    public Result assignRole(AssignRoleVO assignRoleVO) {
        // 获取被分配角色的用户Id
        Long userId = assignRoleVO.getUId();
        try {
            // 删除用户分配的角色
            userRoleService.remove(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userId));
            List<UserRole> userRoles = new ArrayList<>();
            for (Long roleId : assignRoleVO.getRId()) {
                UserRole userRole = new UserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(userId);
                userRoles.add(userRole);
            }

            // 添加新的用户分配的角色
            userRoleService.saveBatch(userRoles);
        } catch (Exception e) {
            // 进行事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error().message("分配角色失败");
        }

        return Result.ok().message("分配角色成功");
    }

    @Override
    @Transactional
    public Boolean removeRole(Long id) {
        try {
            // 删除角色权限中间表
            rolePermissionService.remove(new LambdaQueryWrapper<RolePermission>().eq(RolePermission::getRoleId, id));
            // 删除角色表
            this.removeById(id);
            // 删除用户角色表
            userRoleService.remove(new LambdaQueryWrapper<UserRole>().eq(UserRole::getRoleId, id));
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }

    @Override
    @Transactional
    public Boolean assignPermission(AuthorityVO authorityVO) {
        try {
            Integer roleId = authorityVO.getRId();
            // 删除角色权限表
            rolePermissionService.remove(new LambdaQueryWrapper<RolePermission>().eq(RolePermission::getRoleId, roleId));
            // 获取权限
            List<RolePermission> list = new ArrayList<>();
            for (Integer permissionId : authorityVO.getPId()) {
                RolePermission rolePermission = new RolePermission();
                rolePermission.setPermissionId(permissionId);
                rolePermission.setRoleId(roleId);
                list.add(rolePermission);
            }
            // 存储角色权限表
            rolePermissionService.saveBatch(list);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }

    /**
     * 寻找子树
     *
     * @param parentTree 根节点
     * @param trees      树形集合
     * @return
     */
    private Tree findChildren(Tree parentTree, List<Tree> trees) {
        parentTree.setChildren(new ArrayList<Tree>());
        for (Tree tree : trees) {
            if (tree.getPId().compareTo(parentTree.getId()) == 0) {
                parentTree.getChildren().add(findChildren(tree, trees));
            }
        }
        return parentTree;
    }
}
